package com.android.myipc;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import android.webkit.ServiceWorkerClient;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by Android Studio.
 * User: pengym
 * Date: 2020/11/10
 * Time: 15:57
 * Name: 作用类：
 */
public class BookManagerService extends Service {
    private static final String TAG = "BMS";
    private AtomicBoolean mIsServiceDestoryed = new AtomicBoolean(false);
    private CopyOnWriteArrayList<Book> mBookList = new CopyOnWriteArrayList<Book>();
    //发现，解除注册listener失败，使用RemoteCallbackList
    private RemoteCallbackList<IOnNewBookArrivedListener> mListenerList2 = new RemoteCallbackList<>();

    private CopyOnWriteArrayList<IOnNewBookArrivedListener> mListenerList = new CopyOnWriteArrayList<>();
    //
    private Binder mBinder = new IBookManager.Stub() {
        @Override
        public List<Book> getBookList() throws RemoteException {
            return mBookList;
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            mBookList.add(book);

        }

        @Override
        public void registerListener(IOnNewBookArrivedListener listenenr) throws RemoteException {//拿到数据
            //使用新的listener实现
            mListenerList2.register(listenenr);
//            if (!mListenerList.contains(listenenr)){
//                mListenerList.add(listenenr);
//            }else {
//                Log.d(TAG,"already exists");
//            }
            Log.d(TAG, "registerListener,size:" + mListenerList2.beginBroadcast());
            mListenerList2.finishBroadcast();
        }

        @Override
        public void unregisterListener(IOnNewBookArrivedListener listener) throws RemoteException {
            mListenerList2.unregister(listener);
//            if (mListenerList.contains(listener)){
//                mListenerList.remove(listener);
//                Log.d(TAG,"unregister listener succeed.");
//            }else{
//                Log.d(TAG,"not found, can not unregister.");
//            }
            Log.d(TAG, "unregisterListener,current size:" + mListenerList2.beginBroadcast());
            mListenerList2.finishBroadcast();
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        mBookList.add(new Book(1, "android"));
        mBookList.add(new Book(2, "IOS"));
        new Thread(new ServiceWorker()).start();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private class ServiceWorker implements Runnable {
        @Override
        public void run() {
            while (!mIsServiceDestoryed.get()) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int bookId = mBookList.size() + 1;
                Book newBook = new Book(bookId, "new book#" + bookId);
                try {
                    onNewBookArrived(newBook);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //添加数据，发送给Handler
    private void onNewBookArrived(Book newBook) throws RemoteException {
        mBookList.add(newBook);
        Log.d(TAG, "onNewBookArrived,notify listeners:" + mListenerList.size());
        final int N = mListenerList2.beginBroadcast();
        for (int i = 0; i < N; i++) {
            IOnNewBookArrivedListener l = mListenerList2.getBroadcastItem(i);
            if (l != null) {
                try {
                    l.onNewBookArrived(newBook);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
        mListenerList2.finishBroadcast();
//        for (int i = 0; i < mListenerList.size(); i++) {
//            IOnNewBookArrivedListener listener = mListenerList.get(i);
//            Log.d(TAG, "onNewBookArrived,notify listener:" + listener);
//            listener.onNewBookArrived(newBook);
//
//        }
    }
}
